/*
 * 文件名：CustManagerDaoImp.java
 * 版权：Copyright by www.wootide.com
 * 描述：
 * 修改人：Administrator
 * 修改时间：2013-2-21
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
package com.wootide.cms.service.customer.custmanager.dao.imp;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.wootide.cms.common.Page;
import com.wootide.cms.common.QueryCondition;
import com.wootide.cms.common.QueryResults;
import com.wootide.cms.common.util.CommonUtil;
import com.wootide.cms.log.syslog.RunLog;
import com.wootide.cms.service.customer.custmanager.dao.CustManagerDao;
import com.wootide.cms.service.customer.custmanager.pojo.ClientLevel;
import com.wootide.cms.service.customer.custmanager.pojo.Customer;

public class CustManagerDaoImp extends HibernateDaoSupport implements
        CustManagerDao
{
    /**
     * 日志监控
     */
    private RunLog runLog;
    
    @Override
    public void addOneCustomer(Customer customer)
    {
        this.getHibernateTemplate().save(customer);
        
    }
    
    //    @Override
    //    public QueryResults queryForPages(Page page, QueryCondition queryConditon)
    //    {
    //        return null;
    //    }
    public int findCustomerNumByCardNo(Long cardNo)
    {
        runLog.debug("customer=" + cardNo);
        String sql = "select count(a) from Customer a where a.cardNo = "
                + cardNo +"and a.status <> 2";
        return ((Number)getHibernateTemplate().find(sql).get(0)).intValue();
    }
    
    public RunLog getRunLog()
    {
        return runLog;
    }
    
    public void setRunLog(RunLog runLog)
    {
        this.runLog = runLog;
    }
    
    @Override
    public Customer findOneCustomerByCustomerById(Integer customerId)
    {
        runLog.debug("customerId=" + customerId);
        return this.getHibernateTemplate().get(Customer.class, customerId);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public QueryResults queryForPages(final Page page,
            final QueryCondition queryConditon)
    {
        // 打印方法入口参数
        runLog.debug("page=" + page);
        runLog.debug("queryConditon" + queryConditon);
        
        List queryResults = (List)getHibernateTemplate().execute(new HibernateCallback()
        {
            public Object doInHibernate(Session session) throws SQLException
            {
                //                        Criteria criteria = session
                //                                .createCriteria(queryConditon.getObjClass());
                Criteria criteria = session.createCriteria(queryConditon.getObjClass());
                criteria.add(Restrictions.ne("status", new Integer(2)));
                // 如果查询条件不为空
                if (CommonUtil.conditionExist(queryConditon))
                {
                    String conditionKey = queryConditon.getKey();
                    String strCondition = "%" + queryConditon.getValue().trim()
                            + "%";
                    if (conditionKey.equals("cardNo"))
                    {
                        criteria.add(Restrictions.sqlRestriction("CAST({alias}."
                                + conditionKey + " AS CHAR) like ?",
                                strCondition,
                                Hibernate.STRING));
                    }
                    else
                    {
                        criteria.add(Restrictions.ilike(conditionKey,
                                strCondition));
                    }
                }
                // 获得总记录数
                int totalNum = ((Number)criteria.setProjection(Projections.rowCount())
                        .list()
                        .get(0)).intValue();
                page.setTotalNum(totalNum);
                
                criteria.setProjection(null);
                // 获得分页查询数据
                List results = criteria.setMaxResults(page.getNumPerPage())
                        .setFirstResult(page.getFirstResult())
                        .list();
                return results;
            }
        });
        QueryResults result = new QueryResults();
        result.setResults(queryResults);
        result.setPage(page);
        return result;
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public QueryResults queryCustomerLevel(QueryCondition queryConditon)
    {
        QueryResults results = new QueryResults();
        results.setResults((List)this.getHibernateTemplate()
                .loadAll(queryConditon.getObjClass()));
        return results;
    }
    
    @Override
    public Customer findCustomerByCustomerId(Integer customerId)
    {
        runLog.debug("customerId=" + customerId);
        return this.getHibernateTemplate().get(Customer.class, customerId);
    }
    
    @Override
    public Customer findOneCustomerByCustomerId(Integer customerId)
    {
        runLog.debug("customerId=" + customerId);
        return this.getHibernateTemplate().get(Customer.class, customerId);
    }
    
    @Override
    public ClientLevel findOneLevelByClientLevelId(Integer clientLevelId)
    {
        runLog.debug("clientLevelId=" + clientLevelId);
        return this.getHibernateTemplate()
                .get(ClientLevel.class, clientLevelId);
    }
    
    /**
     * 通过姓名和电话查询客户信息
     * Description: <br>
     * Implement: <br>
     * @param customer 客户信息条件
     * @return
     * @see
     * @return Customer 查询到的客户信息
     * @author ozm2013-3-28下午6:48:09
     */
    @SuppressWarnings("rawtypes")
    public Customer findOneCustomerByNameAndPhoneOrCardNo(Customer customer)
    {
        List list = null;
        if (null != customer.getCardNo())
        {
            list = getHibernateTemplate().findByNamedQuery("findOneCustomerBycardNo",
                    customer.getCardNo());
            
            //            return (Customer)getHibernateTemplate().findByNamedQuery("findOneCustomerBycardNo", customer.getCardNo());
        }
        else
        {
            Object[] values = {customer.getCustName(), customer.getTel()};
            
            list = getHibernateTemplate().findByNamedQuery("findOneCustomerByNameAndPhone",
                    values);
            
        }
        
        if (CommonUtil.collectionIsNull(list))
        {
            return null;
        }
        else
        {
            return (Customer)list.get(0);
        }
    }
}
